package org.harsh.transmission.common.codec;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.harsh.common.Constants;
import org.harsh.transmission.server.NodeServer;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
public class DatagramPacketCodec extends MessageToMessageCodec<DatagramPacket, ByteBuf> {

    private InetSocketAddress remoteAddress;

    public DatagramPacketCodec(InetSocketAddress remoteAddress) {
        this.remoteAddress = remoteAddress;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(remoteAddress != null)
            //fixed something wrong
            list.add(new DatagramPacket(Unpooled.copiedBuffer(byteBuf), remoteAddress));
        else
            channelHandlerContext.flush();
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket, List<Object> list) throws Exception {
        this.remoteAddress = datagramPacket.sender();
        channelHandlerContext.channel().attr(Constants.remoteAddr_key).set(remoteAddress);
        SysDept localDept = NodeServer.localDept;
        if(!this.remoteAddress.getAddress().getHostAddress().equals(localDept.getLocalAddr())) {
            // 为本机发出的，则直接丢弃
            log.info("Receive data from peer , addr : {}", this.remoteAddress.getAddress());
            ByteBuf data = Unpooled.copiedBuffer(datagramPacket.content());
            list.add(data);
        } else {
            log.info("Receive data from local, addr : {}", this.remoteAddress.getAddress());
        }
    }
}
